package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.InvokeMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Invoke;
import io.xxx.xbutler.sdk.TanJingClient;
import io.xxx.xbutler.sdk.request.GetMerchantRobotPageListRequest;
import io.xxx.xbutler.sdk.response.GetMerchantRobotPageListResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商家新增平台机器人回调
 * <p>
 * 商家新增机器人后，开放平台会主动推送此回调通知商家
 *
 * <pre>
 * {
 *     "vcMerchantNo": "202211150061049",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "20231120164327130444010199137",
 *     "nType": 1048,
 *     "nResult": 1,
 *     "vcResult": "Success",
 *     "nTimeStamp": 1700469988178,
 *     "Data": {
 *         "nRobotCount": 500,
 *         "RobotList": [
 *             "74CDA642EB572C75B6F5D558152528FE",
 *             "74E8E81B69BB8269EF69FE89D21DA582"
 *         ],
 *         "nIsImposed": false,
 *         "BusinessType": 0,
 *         "athome_abroad_type": 0
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1048Handler implements CallbackHandler {

    @Resource
    private TanJingClient client;

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private InvokeMapper invokeMapper;

    @Override
    public String name() {
        return "商家新增平台机器人回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1048;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();
        List<String> robotSerialNos = data.getList("RobotList", String.class);

        GetMerchantRobotPageListRequest request = new GetMerchantRobotPageListRequest()
                .setRobotSerialNos(robotSerialNos)
                .setType(0)
                .setPageSize(500)
                .setMaxId(0L);
        GetMerchantRobotPageListResponse response = client.execute(request);
        Invoke invoke = new Invoke()
                .setId(idGenerator.next())
                .setSerialNo(response.getSerialNo())
                .setRobotId(callback.getRobotId())
                .setRobotSerialNo(callback.getRobotSerialNo())
                .setParams(JSON.parseObject(JSON.toJSONString(request.params())))
                .setCreatedTime(now);
        invokeMapper.insert(invoke);
        if (!response.isSuccess()) {
            log.error("获取商家机器人详情列表失败[callbackId:{}, request:{}, response:{}]", callback.getId(), JSON.toJSONString(request), JSON.toJSONString(response));
        }
    }
}
